package com.cy.sys.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cy.common.pojo.JsonResult;
import com.cy.sys.pojo.SysUser;
import com.cy.sys.service.SysUserService;
import com.google.code.kaptcha.Constants;

import io.micrometer.core.instrument.util.StringUtils;

/**
 * 此类处理用户模块的请求
 * @author private
 *
 */
@RestController
@RequestMapping("/user/")
public class SysUserController {
	@Autowired
	private SysUserService sysUserService;

	/** 处理修改密码操作 */
	@RequestMapping("doUpdatePassword")
	public JsonResult doUpdatePassword(String pwd, String newPwd, String cfgPwd) {
		//1.将数据信息传递到Service层
		sysUserService.doUpdatePassword(pwd,newPwd,cfgPwd);
		return new JsonResult("update ok");
	}
	
	@RequestMapping("doLogin")
	public JsonResult doLogin(String username,String password,String validateCode, Boolean isRememberMe,HttpServletRequest request) {
		HttpSession session = request.getSession();
		String key = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if(StringUtils.isEmpty(key)|| !key.equalsIgnoreCase(validateCode))
			throw new IllegalArgumentException("验证码输入有误");
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		token.setRememberMe(isRememberMe);
		subject.login(token);
		return new JsonResult("login ok");
	}
	
	/** 处理请求用户分页数据 */
	@RequestMapping("doFindPageObjects")
	public JsonResult doFindPageObjects(String username,Integer pageCurrent,Integer pageSize) {
		return new JsonResult(sysUserService.doFindPageObjects(username, pageCurrent, pageSize));
	}
	
	/** 处理禁用用户 */
	@RequestMapping("doValidById")
	public JsonResult doValidById(Integer id,Integer valid) {
		sysUserService.doValidById(id,valid);
		return new JsonResult("update ok");
	}
	
	/** 处理新增用户 */
	@RequestMapping("doSaveObject")
	public JsonResult doSaveObject(SysUser sysUser,Integer... roleIds) {
		sysUserService.doSaveObject(sysUser,roleIds);
		return new JsonResult("update ok");
	}
	
	/** 根据id查询用户信息进行回显 */
	@RequestMapping("doFindObjectById")
	public JsonResult doFindObjectById(Integer id) {
		return new JsonResult(sysUserService.doFindObjectById(id));
	}
	
	/** 进行用户的修改 */
	@RequestMapping("doUpdateObject")
	public JsonResult doUpdateObject(SysUser sysUser,Integer... roleIds) {
		sysUserService.doUpdateObject(sysUser,roleIds);
		return new JsonResult("update ok");
	}
	
}
